<template>
    <div class="timeoutreplay-container" :style="{ paddingTop: notOpenedVue !== 1 ? '36px' : '' }">
        <div v-if="notOpenedVue !== 1" class="header-tips">
            <el-icon><Warning /></el-icon>
            <div class="text">要使用当前动能，请先开通会话存档</div>
            <span @click="$router.push('/channelconfig/qywechat/messagesave')">去配置</span>
        </div>
        <ZWSearch row-num="3" :option="searchOption" @search="search" @reset="reset"></ZWSearch>
        <div class="btn-wrap d-flex flex-end">
            <el-button v-if="notOpenedVue == 1 ? true : false" :disabled="!checkList.length" @click="batchDel">
                批量删除
            </el-button>
            <el-button type="primary" :disabled="notOpenedVue == 1 ? false : true" @click="goNew"> 新建规则 </el-button>
        </div>
        <ZWTable
            ref="orderTableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @select-all="onSelectAll"></ZWTable>
        <Dialog :app-dialog="appDialogDeleteStore">
            <div class="tips">{{ tips }}</div>
        </Dialog>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'TIMEOUT_REPLAY' });
</script>

<script lang="tsx" setup>
import lodash from 'lodash';
import { ElButton, ElMessage, ElPopover } from 'element-plus';
import { computed, reactive, ref, onMounted, onActivated } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import ZWTable from '@/components/zw/table/Table';
import router from '@/router';
import { getRuleList, delRule } from '@/api/employe/staffsupervision/timeoutreplay';
import { getCreateList } from '@/api/common';
import { deepCopy } from '@/utils/helper';
import { whetherOpen } from '@/api/employe/riskmonitoring/messagearchiving';
const orderTableRef = ref<HTMLElement | null>(null);
const notOpenedVue = ref(1);
onMounted(() => {
    whetherOpen().then((data: any) => {
        notOpenedVue.value = data.is_open;
    });
});

const goNew = () => {
    router.push('/employee/staffsupervision/timeoutreplay/createreplay');
};
const goStatic = (row: any) => {
    const params = {
        title: encodeURIComponent(row.title),
        created_name: encodeURIComponent(row.created_name),
        created_at: decodeURIComponent(row.created_at),
        id: row.id
    };
    router.push({
        path: '/employee/staffsupervision/timeoutreplay/replaystatiscal',
        query: params
    });
};
const defaultParams = {};
type stateType = {
    searchParams: any;
    deleteId: number | string;
};

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const state = reactive<stateType>({
    searchParams: lodash.cloneDeep(defaultParams),
    deleteId: ''
});
const checkList = ref<any>([]);

let targetArr = reactive([]);

const isbatchDel = ref(false);

const reset = (): void => {
    orderTableRef.value?.clearSelection();
    state.searchParams = lodash.cloneDeep(defaultParams);
    currentParams.value = null;
};

// 获取创建人列表
const getCreator = () => {
    getCreateList({}).then((res: any) => {
        targetArr = res;
    });
};

getCreator();

const tips = ref<string>('确定删除所选数据吗？');

const cancelHandelDelete = (): void => {
    appDialogDeleteStore.visible = false;
    state.deleteId = '';
};
const delTimeoutPlay = (row: any) => {
    const { id: deleteId } = row;
    state.deleteId = deleteId;
    isbatchDel.value = false;
    appDialogDeleteStore.visible = true;
};

const submitHandelDelete = async () => {
    if (!isbatchDel.value) {
        delRule({ timeout_remind_rule_ids: [state.deleteId] }).then((res: any) => {
            ElMessage.success('删除成功');
            orderTableRef.value?.clearSelection();
            search({ ...state.searchParams });
            state.deleteId = '';
            cancelHandelDelete();
        });
    } else {
        del();
        cancelHandelDelete();
    }
};

const appDialogDeleteStore = reactive<any>({
    visible: false,
    title: '删除规则',
    width: '500px',
    cancel: cancelHandelDelete,
    submit: submitHandelDelete,
    cancelText: '取消',
    submitText: '确定'
});

const searchOption = computed(() => {
    return [
        {
            label: '规则搜索',
            name: 'keywords',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称',
            disabled: notOpenedVue.value == 1 ? false : true
        },
        {
            label: '创建人',
            name: 'created_uids',
            value: '',
            type: 'select',
            filterable: true,
            multiple: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve(targetArr);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            }),
            disabled: notOpenedVue.value == 1 ? false : true
        },
        {
            label: '创建时间',
            name: 'created_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            disabled: notOpenedVue.value == 1 ? false : true
        },
        {
            label: '适用员工',
            name: 'executor_uids',
            value: '',
            type: 'select',
            placeholder: '全部',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            is_open_session_archive: 1,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            }),
            disabled: notOpenedVue.value == 1 ? false : true
        }
    ];
});

const tableOption = [
    {
        type: 'selection',
        width: 65,
        fixed: 'left',
        reserveSelection: true,
        disabled: notOpenedVue.value == 1 ? false : true
    },
    {
        prop: 'title',
        label: '规则名称',
        width: 180
    },
    {
        prop: 'executor_list',
        label: '适用员工',
        minWidth: 180,
        render({ row }: any) {
            let name = '';
            row.executor_list.forEach((e: any, index: any) => {
                if (index <= 2) {
                    const comm = index < row.executor_list.length - 1 ? '，' : '';
                    name = name + e.name + comm;
                }
            });
            return name + '等' + row?.executor_list.length + '位员工';
        }
    },
    {
        prop: 'no_remind_date',
        label: '不提醒日期',
        width: 220,
        render({ row }: any) {
            const date = '';
            const slotReference = () => (
                <div>
                    {row.is_no_remind != 2
                        ? '--'
                        : row.no_remind_date.map((item: any, index: any) => {
                              if (index <= 1) {
                                  return (
                                      <div class="view_address">
                                          <p>{item[0] + '，' + item[1]}</p>
                                      </div>
                                  );
                              }
                          })}
                </div>
            );
            const slotDefault = () => (
                <div class="view_slot_wrap">
                    {row.is_no_remind != 2
                        ? '--'
                        : row.no_remind_date.map((item: any) => {
                              return (
                                  <div class="view_address">
                                      <p>{item[0] + '，' + item[1]}</p>
                                  </div>
                              );
                          })}
                </div>
            );
            return (
                <ElPopover
                    popper-class="popGroup"
                    trigger="hover"
                    vSlots={{ reference: slotReference, default: slotDefault }}
                    width={'auto'}
                    popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
            );
        }
    },
    {
        prop: 'over_time',
        label: '超时规则',
        minWidth: 150,
        render({ row }: any) {
            const d = row.time_unit == 1 ? '分钟' : '小时';
            return '超过' + row.over_time + d + '未回复';
        }
    },
    {
        prop: 'end_words',
        label: '正常结束语',
        width: 200,
        render({ row }: any) {
            const date = '';
            const slotReference = () => (
                <div>
                    {row.is_open_end_words != 2
                        ? '--'
                        : row.end_words.map((item: any, index: any) => {
                              if (index <= 1) {
                                  return (
                                      <div class="view_address">
                                          <p>【{item}】</p>
                                      </div>
                                  );
                              }
                          })}
                </div>
            );
            const slotDefault = () => (
                <div class="view_slot_wrap">
                    {row.is_open_end_words != 2
                        ? '--'
                        : row.end_words.map((item: any) => {
                              return (
                                  <div class="view_address">
                                      <p>【{item}】</p>
                                  </div>
                              );
                          })}
                </div>
            );
            return (
                <ElPopover
                    popper-class="popGroup"
                    trigger="hover"
                    vSlots={{ reference: slotReference, default: slotDefault }}
                    width={'auto'}
                    popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
            );
        }
    },
    {
        prop: 'created_name',
        label: '创建人',
        width: 160
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        align: 'left',
        fixed: 'right',
        width: 220,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <>
                    <ElButton
                        class="sopBtn"
                        size="small"
                        onClick={() => {
                            const path = '/employee/staffsupervision/timeoutreplay/createreplay';
                            const query = { id: row.id, type: 'edit' };
                            router.push({ path, query });
                        }}
                        disabled={notOpenedVue.value == 1 ? false : true}>
                        编辑
                    </ElButton>
                    <ElButton
                        class="sopBtn"
                        size="small"
                        onClick={() => goStatic(row)}
                        disabled={notOpenedVue.value == 1 ? false : true}>
                        统计
                    </ElButton>
                    <ElButton
                        class="sopBtn"
                        size="small"
                        onClick={() => {
                            delTimeoutPlay(row);
                        }}
                        disabled={notOpenedVue.value == 1 ? false : true}>
                        删除
                    </ElButton>
                </>
            );
        }
    }
];

const search = (data: any) => {
    orderTableRef.value?.clearSelection();
    if (data.created_at && data.created_at.length > 1) {
        const date = data.created_at[1].split(' ');
        const time = date[0] + ' 23:59:59';
        data.created_at = [data.created_at[0], time];
    }
    currentParams.value = data;
    state.searchParams = lodash.cloneDeep(data);
};
// 选中表格 checkbox
const onSelect = (selection: any, row: any) => {
    isbatchDel.value = true;
    checkList.value = selection;
};
// 全选
const onSelectAll = (selection: any) => {
    isbatchDel.value = true;
    checkList.value = selection;
};

const batchDel = () => {
    if (checkList.value.length <= 0) {
        ElMessage.warning('请选择需要删除的数据');
        return;
    }
    appDialogDeleteStore.visible = true;
};
const del = () => {
    delRule({
        timeout_remind_rule_ids: checkList.value.map((v: any) => v.id)
    }).then((res: any) => {
        ElMessage.success('删除成功');
        orderTableRef.value?.clearSelection();
        state.searchParams = { ...state.searchParams };
    });
};

const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = (): any => {
    return new Promise((resolve: any): any => {
        const page_size: string | number = 15;
        const params = {};
        resolve([params, getRuleList]);
    });
};

onActivated((val: any) => {
    whetherOpen().then((data: any) => {
        notOpenedVue.value = data.is_open;
    });
    orderTableRef.value?.clearSelection();
    // if (currentParams.value.created_at && currentParams.value.created_at.length > 1) {
    //   let date = currentParams.value.created_at[1].split(" ");
    //   let time = date[0] + " 23:59:59";
    //   currentParams.value.created_at = [currentParams.value.created_at[0], time];
    // }
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style lang="scss" scoped>
.btn-wrap {
}

.ai-center {
    align-items: center;
}

.d-flex {
    display: flex;
}

.flex-end {
    justify-content: flex-end;
}

.timeoutreplay-container {
    position: relative;
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    .header-tips {
        width: 100%;
        height: 40px;
        background: #fffbe6;
        border-radius: 2px;
        border: 1px solid #ffe58f;
        font-size: 14px;
        font-weight: 400;
        color: rgb(0 0 0 / 65%);
        line-height: 40px;
        padding: 0 17px;
        display: flex;
        align-items: center;
        position: absolute;
        top: -20px;
        left: -20px;

        .text {
            margin-left: 8px;
        }

        span {
            font-size: 14px;
            font-weight: 400;
            color: #1890ff;
            line-height: 22px;
            margin-left: 15px;
            cursor: pointer;
        }
    }
}

:deep(.detail_address) {
    // width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

:deep(.view_address) {
    border-bottom: 1px solid #eaeaea;
}

.view_slot_wrap {
    max-height: 300px;
    overflow-y: auto;
}
</style>
